package com.lanyeo.liver.util

import android.content.Context
import java.io.File
import java.io.PrintWriter
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class AppCrashHandler(private val context: Context) : Thread.UncaughtExceptionHandler {

    val defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()

    override fun uncaughtException(t: Thread, e: Throwable) {
        val path = context.applicationContext?.getExternalFilesDir("error")?.absolutePath
        path?.let {
            val logDir = File(path)
            if (!logDir.exists()) {
                logDir.mkdirs()
            }
            val logPath = File(path + File.separator + "error.log")
            val writer = logPath.writer()
            val printWriter = PrintWriter(writer)
            val nowTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.[SSS]").format(LocalDateTime.now())
            printWriter.write("--------------------------{}---------------------------\n".format(nowTime))
            e.printStackTrace(printWriter)
            printWriter.write("-------------------------------------------------------\n")
            printWriter.flush()
            printWriter.close()
            defaultUncaughtExceptionHandler?.uncaughtException(t, e)
        }
    }
}